package top.withu.gaof.freehope.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import top.withu.gaof.freehope.dao.ArticleContentDao;
import top.withu.gaof.freehope.dao.ArticleDao;
import top.withu.gaof.freehope.model.ArticleContent;
import top.withu.gaof.freehope.model.ArticleModel;
import top.withu.gaof.freehope.res.ArticleRes;
import top.withu.gaof.freehope.service.ArticleService;
import top.withu.gaof.freehope.vo.ArticleVo;

import javax.annotation.Resource;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleDao articleDao;
    @Resource
    private ArticleContentDao articleContentDao;


    @Override
    public List<ArticleRes> getAll() {
        List<ArticleRes> articleRes = new ArrayList<ArticleRes>();
        List<String> articleType = articleDao.findArticleType(Boolean.TRUE);
        for (String str : articleType) {
            ArticleRes res = new ArticleRes();
            res.setArticleType(str);
            res.setArticleModels(articleDao.findByArticleTypeAndIsEnabled(str, Boolean.TRUE));
            articleRes.add(res);
        }
        return articleRes;
    }

    @Override
    public int updateArticle(ArticleVo vo) {
        if(null == vo){
            return 0;
        }
        ArticleModel model = new ArticleModel();
        BeanUtils.copyProperties(vo, model);
        articleDao.save(model);
        ArticleContent content = new ArticleContent();
        content.setHtmlContent(vo.getHtmlContent());
        content.setMKContent(vo.getMKContent());
        content.setArticleId(model.getId());
        return articleContentDao.save(content) != null ? 1 : 0;
    }

    @Override
    public ArticleModel findOne(String id) {
        return articleDao.findOneById(Integer.valueOf(id));
    }

    @Override
    public int countAll() {
        return (int) articleDao.count();
    }
}
